/**
 * 设置数据
 * @param {*} elObj
 * @param {Array} data
 * @param value
 */
const setData = function(elObj, data, value) {
	elObj.empty();
	for (let i = 0; i < data.length; i++) {
		const item = data[i];
		elObj.append(`<option value="${item.title}">${item.title}</option>`);
	}
	if (value !== undefined) elObj.val(value);
};

/**
 * 初始化区域列表
 * @param {Object} options
 */
_.region = function(options) {
	if (!window.REGION) throw new Error("找不到 REGION 数据");

	let provinceEl = $(options.province.el),
		cityEl = $(options.city ? options.city.el : ''),
		areaEl = $(options.area ? options.area.el : ''),
		provinceIndex,
		cityIndex = 0,
		filterKey = "region_" + new Date().getTime();


	//初始化数据
	(function() {

		//省份
		provinceEl.attr('lay-filter', filterKey).attr('level', 1);
		setData(provinceEl, REGION, options.province.value);
		provinceIndex = provinceEl.prop('selectedIndex');
		if (provinceIndex < 0) return;

		//城市
		if (options.city) {
			cityEl.attr('lay-filter', filterKey).attr('level', 2);
			setData(cityEl, REGION[provinceIndex].child, options.city.value);
			cityIndex = cityEl.prop('selectedIndex');
		}

		// //城镇
		if (options.city && options.area) {
			areaEl.attr('lay-filter', filterKey).attr('level', 3);
			setData(areaEl, window.REGION[provinceIndex].child[cityIndex].child, options.area.value);
		}

	})();

	//添加事件
	if (window.layui) {
		layui.form.on('select(' + filterKey + ')', function(data) {
			const self = $(data.elem),
				level = parseInt(self.attr('level')),
				index = data.elem.selectedIndex,
				filter = self.closest('.layui-form').attr('lay-filter');

			if (level === 1) {
				provinceIndex = index;
				if (options.city) {
					setData(cityEl, REGION[index].child);
					if (options.area) setData(areaEl, REGION[index].child[0].child);
					layui.form.render(null, filter);
				}
			} else if (level === 2) {
				cityIndex = index;
				if (options.area) {
					setData(areaEl, REGION[provinceIndex].child[index].child);
					layui.form.render(null, filter);
				}
			}
		});
	} else {
		provinceEl.on('change', function() {
			const provinceIndex = this.selectedIndex;
			if (options.city) {
				setData(cityEl, REGION[provinceIndex].child);
				if (options.area) setData(areaEl, REGION[provinceIndex].child[0].child);
			}
		});
		cityEl.on('change', function() {
			const cityIndex = this.selectedIndex;
			if (options.area) setData(areaEl, REGION[provinceIndex].child[cityIndex].child);
		});
	}
};
